package com.cpm.offcn.workqueue;

import com.cpm.offcn.utils.RabbitUtils;
import com.rabbitmq.client.*;

import java.io.IOException;

public class SMSSender02 {
    public static void main(String[] args) throws IOException {
        //获取tcp长连接
        Connection connection = RabbitUtils.getConnection();
        //创建信道
        final Channel channel = connection.createChannel();
        //绑定信道
        channel.queueDeclare("QUEUE_SMS", false, false, false, null);

        //如果不定义，那么mq会自动将所有消息平均发送给所有消费者
        //mq不在对消费者一次性发送多个请求，而是消费者在处理完一个请求后，在队列中获取一个信道
        channel.basicQos(1);

        //开启一个消费者
        channel.basicConsume("QUEUE_SMS",false,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String jsonSMS = new String(body);
                System.out.println("信息消费成功："+jsonSMS);

                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //签收消息
                channel.basicAck(envelope.getDeliveryTag() , false);
            }
        });


    }
}
